package Run_System;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;

import com.csvreader.*;
public class FileOperator {

    public static void writeExercisesFile(Iterator<Equation> iterator) throws Exception { //将习题写入到文件中
        try {
            Date date = new Date();
            String filePath = "src\\main\\resources\\" + (date.getMonth() + 1) + date.getDate() + "exercises.csv";
            CsvWriter writer = new CsvWriter(filePath, ',', Charset.forName("GBK"));
            String [] header = {"左操作数","运算符","右操作数","结果"};  //写入表头
            writer.writeRecord(header);
            int i = 0;
             while (iterator.hasNext()){
                 Equation equation = iterator.next();
                String[] content = {equation.getLeft_operand()+"",Character.toString(equation.getOperator()),
                        ""+equation.getRight_operand(),""+equation.getValue()};  //写入算式 左操作数 符号位 右操作数 和 结果,用逗号作为分隔符
                 writer.writeRecord(content);
            }
             writer.close();
        }catch (Exception e){
            throw  e;
        }
    }

    public static Exercises readExercises(String filepath) throws Exception{  //从文件中读取习题
        try {
            Exercises exercises = new Exercises();
            CsvReader reader = new CsvReader(filepath,',',Charset.forName("GBK"));
            reader.readHeaders();
            while (reader.readRecord()){
                String arr[] =  reader.getRawRecord().split(","); //读取字符串，并用空格分割
                int left = Integer.parseInt(arr[0]);    //分别获取左操作数
                char operator = arr[1].charAt(0);       //运算符
                int right = Integer.parseInt(arr[2]);   //右操作数
                int value = Integer.parseInt(arr[3]);   //结果
                Equation equation ;
                switch (operator){                      //根据运算符判断生成算式类型，如果失败则抛出异常
                    case '+' : equation = new AddEquation(left,operator,right,value);break;
                    case '-' : equation = new SubstractEquation(left,operator,right,value);break;
                    case '*' : equation = new MultiplyEquation(left,operator,right,value);break;
                    case '/' : equation = new DividEquation(left,operator,right,value);break;
                    default  : throw new Exception("读入算式有误");
                }
                exercises.addEquation(equation);
            }
            reader.close();
            return exercises;
        }catch (Exception e){
            throw  e;
        }
    }

    public static ArrayList<String> readExercisesFile(){  //从习题文件夹中获取所有的习题文件
        File file = new File("src\\main\\resources");
        String [] files = file.list();
        ArrayList<String> exercisesFile = new ArrayList<>();
        String pattern = ".*exercises.csv.*";
        for(String str : files){
            if(Pattern.matches(pattern,str)){
                exercisesFile.add(str);
            }
        }
        return exercisesFile;
    }

    public static void writeAnswer(ArrayList<Integer> answers) throws  Exception{   //将答案写入文件中
        try{
            Date date = new Date();
            String filePath = "src\\main\\resources\\" + (date.getMonth() + 1) + date.getDate() + "answers.csv";
            CsvWriter writer = new CsvWriter(filePath,',',Charset.forName("GBK"));
            String[] header = {"索引","答案"};
            writer.writeRecord(header);
            for(int i = 0; i < answers.size(); i++){
                String []answer  = {""+(i+1),String.valueOf(answers.get(i))};
                writer.writeRecord(answer);
            }
            writer.close();
        }catch (Exception e){
            throw  e;
        }
    }

    public static ArrayList<Integer> readAnswers(String filePath) throws Exception{ //读取答案
        try {
            CsvReader reader = new CsvReader(filePath, ',', Charset.forName("GBK"));
            ArrayList<Integer> list = new ArrayList<>(50);
            reader.readHeaders();
            while (reader.readRecord()) {
                String arr[] = reader.getRawRecord().split(","); //读取答案，用空格分割
                int answer = Integer.valueOf(arr[1]);
                if(answer != -1) {      //-1用来标记小明做了多少题，读到-1就该停止读入答案// 了
                    list.add(answer);
                }else{
                    break;
                }
            }
            reader.close();
            return list;
        }catch (Exception e){
            throw  e;
        }
    }

    public static ArrayList<String> answersFile(){  //获取所有的答案文件
        File file = new File("src\\main\\resources");
        String [] files = file.list();
        ArrayList<String> answersFile = new ArrayList<>();
        String pattern = ".*answers.csv.*";
        for(String str : files){
            if(Pattern.matches(pattern,str)){
                answersFile.add(str);
            }
        }
        return answersFile;
    }

    public static void writeResults(ArrayList<Boolean> results) throws  Exception{   //将做题结果写入文件中
        try{
            Date date = new Date();
            String filePath = "src\\main\\resources\\" + (date.getMonth() + 1) + date.getDate() + "results.csv";
            CsvWriter writer = new CsvWriter(filePath,',',Charset.forName("GBK"));
            String[] header = {"索引","正误"};
            writer.writeRecord(header);
            for(int i = 0; i < results.size(); i++){
                String []answer  = {""+(i+1),String.valueOf(results.get(i))};
                writer.writeRecord(answer);
            }
            writer.close();
        }catch (Exception e){
            throw  e;
        }
    }

    public static ArrayList<Boolean> readResults(String filePath) throws Exception{ //读取做题结果
        try {
            CsvReader reader = new CsvReader(filePath, ',', Charset.forName("GBK"));
            ArrayList<Boolean> list = new ArrayList<>(50);
            reader.readHeaders();
            while (reader.readRecord()) {
                String arr[] = reader.getRawRecord().split(","); //读取答案，用空格分割
                list.add(Boolean.valueOf(arr[1]));
            }
            reader.close();
            return list;
        }catch (Exception e){
            throw  e;
        }
    }

    public  static ArrayList<String> resultsFile(){  //获取所有的做题结果文件
        File file = new File("C:\\Users\\76905\\IdeaProjects\\xiaoming want to learn\\src\\main\\resources");
        String [] files = file.list();
        ArrayList<String> resultsFile = new ArrayList<>();
        String pattern = ".*results.csv.*";
        for(String str : files){
            if(Pattern.matches(pattern,str)){
                resultsFile.add(str);
            }
        }
        return resultsFile;
    }

    public static ArrayList<Boolean>  exercisesCorrecting(Iterator<Equation> iterator,ArrayList<Integer> answers) throws Exception{ //批改作业
        ArrayList<Boolean> results = new ArrayList<>();
        for(int i = 0; i < answers.size(); i++){
            if(iterator.hasNext()){
                if(iterator.next().getValue() == answers.get(i)){ //根据算式结果和小明输入答案判断正误
                    results.add(true);
                }
                else {
                    results.add(false);
                }
            }
            else {
                throw new Exception("答案数量大于习题数量");
            }
        }
        return  results;    //返回结果，用于答案文件输出
    }

    public static void main(String[] args) {
        try {
            Exercises exercises = ExervisesFactory.generateExercises(ExervisesFactory.ADD_EXERCISES, 50);
            ArrayList<Integer> answers = new ArrayList<>();
            answers.add(1);
            answers.add(2);
            ArrayList<Boolean> results = exercisesCorrecting(exercises.iterator(), answers);
            writeResults(results);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
